<template>
  <div><el-dialog
    :title="isEdit?'编辑':'新增'"
    :visible="isShowDialog"
    width="50%"
    @close="cancelBtn"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="经纪">
        <el-select v-model="form.agent" placeholder="请选择经纪公司">
          <el-option v-for="item in agentsList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="分类">
        <el-select v-model="form.category" placeholder="请选择分类">
          <el-option v-for="item in categoryList" :key="item.id" :label="item.title" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="标题" prop="title">
        <el-input v-model="form.title" />
      </el-form-item>
      <el-form-item label="标签">
        <el-tag
          v-for="tag in form.tags"
          :key="tag"
          closable
          :disable-transitions="false"
          @close="tagClose(tag)"
        >
          {{ tag }}
        </el-tag>
        <el-input
          v-if="inputVisible"
          ref="saveTagInput"
          v-model="inputValue"
          class="input-new-tag"
          size="small"
          @keyup.enter.native="handleInputConfirm"
          @blur="handleInputConfirm"
        />
        <el-button v-else class="button-new-tag" size="small" @click="showInput">新标签</el-button>
      </el-form-item>
      <el-form-item label="地址">
        <el-row type="flex">
          <el-cascader v-model="cityValue" :options="arr" :props="{label:'name',value:'name'}" @change="cityChange" />
          <el-input v-model="form.address" />
        </el-row>
      </el-form-item>
      <el-form-item label="价格">
        <el-input v-model="form.price" />
      </el-form-item>
      <el-form-item label="描述" prop="desc">
        <el-input v-model="form.desc" />
      </el-form-item>
      <el-form-item label="内容">
        <VueEditor ref="vueEditor" :config="config" />
      </el-form-item>
      <el-form-item label="介绍图片">
        <PhotoUpload ref="imageFile" v-model="form.photos" :mutiple="false" />
      </el-form-item>
      <el-form-item label="封面">
        <PhotoUpload ref="coverFile" v-model="form.image" :mutiple="true" />
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="cancelBtn">取 消</el-button>
      <el-button type="primary" @click="btnOk">确 定</el-button>
    </span></el-dialog>
  </div>
</template>

<script>
import { addProperties, getPropertiesListById, updatePropertiesListById } from '@/api/property'
import mapJson from '../data.json'
import VueEditor from 'vue-word-editor'
import 'quill/dist/quill.snow.css'
export default {
  components: {
    VueEditor
  },
  props: {
    isShowDialog: {
      type: Boolean,
      default: false
    },
    categoryList: {
      type: Array,
      default: null
    },
    agentsList: {
      type: Array,
      default: null
    },
    getPage: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      config: {
      // 上传图片的配置
        uploadImage: {
          url: 'http://localhost:3000/upload',
          name: 'file',
          // res是结果，insert方法会把内容注入到编辑器中，res.data.url是资源地址
          uploadSuccess(res, insert) {
            insert('http://localhost:3000' + res.data.url)
          }
        },

        // 上传视频的配置
        uploadVideo: {
          url: 'http://localhost:3000/upload',
          name: 'file',
          uploadSuccess(res, insert) {
            insert('http://localhost:3000' + res.data.url)
          }
        }
      },
      isEdit: false,
      cityValue: [],
      arr: mapJson.data,
      inputVisible: false,
      propertyTags: [],
      inputValue: '',
      form: {
        'title': '', // 标题
        'desc': '', // 描述
        'image': '', // 图片
        'agent': '', // 属于哪个经纪的 id 值
        'content': '', // 内容
        'address': '', // 地址
        'price': '', // 价格
        'photos': [

        ], // 图片, url 组成数组
        'tags': [
          '交通方便',
          '坐北朝南'
        ], // 标签, 字符串组成数组
        'category': '' // 属于哪个分类 id 值
      },
      rules: {
        title: [
          { required: true, message: '请输入标题名称', trigger: 'blur' }
        ],
        desc: [
          { required: true, message: '请输入描述内容', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 获取指定房产
    async getProperties(editData) {
      this.isEdit = true
      // console.log(161, this.nodeData)
      const data = await getPropertiesListById(editData.id)
      console.log(221, data)
      // console.log(data)
      if (data.agent) {
        data.agent = data.agent.id
      }
      if (data.category) {
        data.category = data.category.id
      }
      // console.log(170, this.$refs.vueEditor)
      var quill = this.$refs.vueEditor.editor
      quill.clipboard.dangerouslyPasteHTML(0, data.content)
      quill.enable(false)
      this.$nextTick(() => {
        quill.enable(true)
      })
      this.$refs.coverFile.fileList = [{ url: data.image }]
      const fileList = []
      data.photos.map(item => {
        fileList.push({ url: item })
      })
      console.log(177, fileList)
      this.$refs.imageFile.fileList = fileList
      this.form = data
      console.log(173, this.form)
    },
    cancelBtn() {
      this.form = {
        'title': '', // 标题
        'desc': '', // 描述
        'image': '', // 图片
        'agent': '', // 属于哪个经纪的 id 值
        'content': '', // 内容
        'address': '', // 地址
        'price': '', // 价格
        'photos': [

        ], // 图片, url 组成数组
        'tags': [

        ], // 标签, 字符串组成数组
        'category': '' // 属于哪个分类 id 值
      }
      this.$refs.coverFile.fileList = []
      this.$refs.imageFile.fileList = []
      var quill = this.$refs.vueEditor.editor
      quill.deleteText(0, 99999)
      // 清理报错
      this.$refs.form.resetFields()
      this.isEdit = false
      this.$parent.isShowDialog = false
    },
    onSubmit() {
      console.log('submit!')
    },
    tagClose(tag) {
      this.form.tags.splice(this.form.tags.indexOf(tag), 1)
    },
    showInput() {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    cityChange(value) {
      console.log(153, value)
      this.form.address = value.join('')
    },
    handleInputConfirm() {
      const inputValue = this.inputValue
      if (inputValue) {
        this.form.tags.push(inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
    },
    async btnOk() {
      if (this.isEdit) {
        // 编辑
        console.log('编辑')
        this.form.image = this.$refs.coverFile.fileList[0].url
        this.form.photos = this.$refs.imageFile.fileList.map(item => {
          return item.url
        })
        this.form.content = this.$refs.vueEditor.editor.root.innerHTML
        console.log(227, this.form)
        await updatePropertiesListById(this.form)
        this.$message({
          message: '修改成功',
          type: 'success'
        })
        this.$parent.isShowDialog = false
        this.$parent.getPropertiesList(this.getPage)
      } else {
        // 新增
        // console.log(157, this.$refs.coverFile)
        try {
          this.form.image = this.$refs.coverFile.fileList[0].url
          this.form.photos = this.$refs.imageFile.fileList.map(item => {
            return item.url
          })
          this.form.content = this.$refs.vueEditor.editor.root.innerHTML
          console.log(239, this.form)
          await addProperties(this.form)
          this.$message({
            message: '添加成功',
            type: 'success'
          })
          await this.$parent.getPropertiesCount()
          this.$parent.currentPage = Math.ceil(this.$parent.total / this.getPage._limit)
          this.getPage._start = (this.$parent.currentPage - 1) * this.getPage._limit
          console.log(266, this.getPage)
          this.$parent.getPropertiesList(this.getPage)
          this.$parent.isShowDialog = false
          // this.$parent.getPropertiesList(this.getPage)
        } catch (error) {
          this.$message({
            message: '请等待图片上传完成',
            type: 'info'
          })
          console.log(error)
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
</style>
